<template>
  <div class="ai-chat-container" :class="{ 'expanded': isExpanded }">
    <!-- 折叠状态的图标按钮 -->
    <div class="chat-toggle" @click="toggleChat" v-if="!isExpanded">
      <div class="chat-icon">
        <i class="fas fa-robot"></i>
      </div>
    </div>
    
    <!-- 展开的聊天框 -->
    <div class="chat-box" v-if="isExpanded">
      <div class="chat-header">
        <div class="chat-title">
          <i class="fas fa-robot"></i>
          <span>碳源AI助手</span>
        </div>
        <div class="chat-actions">
          <button class="minimize-btn" @click="toggleChat">
            <i class="fas fa-minus"></i>
          </button>
        </div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-content">{{ message.content }}</div>
        </div>
        <div v-if="isLoading" class="message ai-message">
          <div class="message-content typing">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <textarea 
          v-model="userInput" 
          placeholder="输入您的问题..." 
          @keydown.enter.prevent="sendMessage"
          :disabled="isLoading"
        ></textarea>
        <button @click="sendMessage" :disabled="isLoading || !userInput.trim()">
          <i class="fas fa-paper-plane"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { deepSeekApi } from '@/api/ai';

export default {
  name: 'AiChatBox',
  data() {
    return {
      isExpanded: false,
      messages: [
        { role: 'assistant', content: '您好！我是碳源AI助手，有什么可以帮助您的？' }
      ],
      userInput: '',
      isLoading: false,
      chatHistory: []  // 用于保存发送给API的消息历史
    };
  },
  watch: {
    // 监听消息变化，自动滚动到底部
    messages: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    // 监听展开状态，当展开时滚动到底部
    isExpanded(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    }
  },
  methods: {
    toggleChat() {
      this.isExpanded = !this.isExpanded;
    },
    scrollToBottom() {
      if (this.$refs.messagesContainer) {
        this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
      }
    },
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;
      
      // 添加用户消息
      const userMessage = this.userInput.trim();
      this.messages.push({ role: 'user', content: userMessage });
      
      // 更新历史记录
      this.chatHistory.push({ role: 'user', content: userMessage });
      
      // 清空输入框
      this.userInput = '';
      
      // 显示加载状态
      this.isLoading = true;
      
      try {
        // 调用API服务
        const response = await deepSeekApi.sendMessage(userMessage);
        
        // 添加AI回复
        if (response) {
          const assistantMessage = { role: 'assistant', content: response };
          this.messages.push(assistantMessage);
          this.chatHistory.push(assistantMessage);
        } else {
          const errorMessage = { role: 'assistant', content: '抱歉，我无法处理您的请求，请稍后再试。' };
          this.messages.push(errorMessage);
          this.chatHistory.push(errorMessage);
        }
      } catch (error) {
        console.error('AI API请求失败:', error);
        const errorMessage = { role: 'assistant', content: '抱歉，连接服务器时出现问题，请稍后再试。' };
        this.messages.push(errorMessage);
        this.chatHistory.push(errorMessage);
      } finally {
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.ai-chat-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 折叠状态的图标按钮 */
.chat-toggle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #4CAF50;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.chat-toggle:hover {
  transform: scale(1.05);
  background-color: #3d8b40;
}

.chat-icon {
  color: white;
  font-size: 24px;
}

/* 展开的聊天框 */
.chat-box {
  width: 350px;
  height: 500px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
  animation: slide-up 0.3s ease;
}

@keyframes slide-up {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-header {
  padding: 15px;
  background-color: #4CAF50;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.chat-title i {
  margin-right: 8px;
  font-size: 18px;
}

.chat-actions button {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 16px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.chat-actions button:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message {
  max-width: 80%;
  padding: 10px 12px;
  border-radius: 10px;
  word-wrap: break-word;
}

.user-message {
  align-self: flex-end;
  background-color: #4CAF50;
  color: white;
}

.ai-message {
  align-self: flex-start;
  background-color: white;
  border: 1px solid #e0e0e0;
  color: #333;
}

.typing {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 20px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #aaa;
  border-radius: 50%;
  margin: 0 3px;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); }
  40% { transform: scale(1.2); }
}

.chat-input {
  padding: 15px;
  display: flex;
  border-top: 1px solid #e0e0e0;
}

.chat-input textarea {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  padding: 10px 15px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  height: 40px;
  line-height: 20px;
  max-height: 120px;
  outline: none;
}

.chat-input textarea:focus {
  border-color: #4CAF50;
}

.chat-input button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #4CAF50;
  color: white;
  border: none;
  margin-left: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.chat-input button:not(:disabled):hover {
  background-color: #3d8b40;
}

@media (max-width: 480px) {
  .chat-box {
    width: 300px;
    height: 450px;
  }
  
  .chat-toggle {
    width: 50px;
    height: 50px;
  }
  
  .chat-icon {
    font-size: 20px;
  }
}
</style> 